import 'package:flutter/material.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:url_launcher/url_launcher.dart';
import '../models/document_detail.dart';

class DocumentDetailView extends StatefulWidget {
  final DocumentDetail? detail;
  final bool isLoading;
  final String? error;
  final bool isPreviewMode;
  final VoidCallback? onTogglePreviewMode;
  final TextEditingController? contentController;
  final TextEditingController? nameController;

  const DocumentDetailView({
    super.key,
    this.detail,
    this.isLoading = false,
    this.error,
    this.isPreviewMode = true,
    this.onTogglePreviewMode,
    this.contentController,
    this.nameController,
  });

  @override
  State<DocumentDetailView> createState() => _DocumentDetailViewState();
}

class _DocumentDetailViewState extends State<DocumentDetailView> {

  Future<void> _launchUrl(String urlString) async {
    final Uri url = Uri.parse(urlString);
    if (!await launchUrl(url, mode: LaunchMode.externalApplication)) {
      throw Exception('Could not launch $urlString');
    }
  }

  @override
  Widget build(BuildContext context) {
    if (widget.isLoading) {
      return const Center(
        child: CircularProgressIndicator(),
      );
    }

    if (widget.error != null) {
      return Center(
        child: Text(
          '加载失败: ${widget.error}',
          style: const TextStyle(color: Colors.red),
        ),
      );
    }

    if (widget.detail == null) {
      return const Center(
        child: Text('请选择文档'),
      );
    }

    // 编辑模式
    if (!widget.isPreviewMode && widget.contentController != null) {
      return TextField(
        controller: widget.contentController,
        style: const TextStyle(
          fontSize: 14,
          height: 1.75,
          color: Color(0xFF353535),
        ),
        decoration: const InputDecoration(
          hintText: '请输入文档内容...',
          border: InputBorder.none,
          contentPadding: EdgeInsets.all(16.0),
        ),
        maxLines: null,
        expands: true,
        textAlignVertical: TextAlignVertical.top,
      );
    }

    // 预览模式
    return GestureDetector(
      onDoubleTap: widget.onTogglePreviewMode,
      child: SelectionArea(
        child: Markdown(
          data: widget.detail!.content,
          selectable: false,
          padding: const EdgeInsets.all(16.0),
          onTapLink: (text, href, title) {
            if (href != null) {
              _launchUrl(href);
            }
          },
          styleSheet: MarkdownStyleSheet(
              // 段落样式
              p: const TextStyle(
                fontSize: 14,
                color: Color(0xFF353535),
                height: 1.75,
                letterSpacing: 0.8,
              ),
              // 链接样式
              a: const TextStyle(
                color: Color(0xFF37352F),
                decoration: TextDecoration.underline,
                decorationColor: Color(0x6637352F),
              ),
              // 粗体样式 - 带黄色背景
              strong: const TextStyle(
                fontWeight: FontWeight.bold,
                backgroundColor: Color(0xFFFFF3E0),
              ),
              // 斜体样式 - 红色
              em: const TextStyle(
                fontStyle: FontStyle.italic,
                color: Color(0xFFF83929),
              ),
              // 标题样式
              h1: const TextStyle(
                fontSize: 22,
                fontWeight: FontWeight.w300,
                color: Color(0xFF353535),
              ),
              h2: const TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w700,
                color: Color(0xFF353535),
              ),
              h3: const TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w600,
                color: Color(0xFF353535),
              ),
              h4: const TextStyle(
                fontSize: 15,
                fontWeight: FontWeight.w600,
                color: Color(0xFF353535),
              ),
              h5: const TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w600,
                color: Color(0xFF353535),
              ),
              h6: const TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w600,
                color: Color(0xFF353535),
              ),
              // 列表样式
              listBullet: const TextStyle(
                fontSize: 14,
                color: Color(0xFFF83929),
              ),
              // 引用样式
              blockquote: const TextStyle(
                fontSize: 14,
                color: Color(0xFF353535),
                height: 1.75,
              ),
              blockquoteDecoration: BoxDecoration(
                color: const Color(0xFFF5F5F5),
                borderRadius: BorderRadius.circular(13),
              ),
              blockquotePadding: const EdgeInsets.fromLTRB(10, 10, 10, 25),
              // 代码块样式
              code: const TextStyle(
                fontFamily: 'monospace',
                fontSize: 12,
                color: Color(0xFF383A42),
                backgroundColor: Color(0xFFEEEEEE),
              ),
              codeblockDecoration: BoxDecoration(
                color: const Color(0xB3EEEEEE),
                borderRadius: BorderRadius.circular(5),
              ),
              codeblockPadding: const EdgeInsets.all(16),
              // 行内代码样式
              codeblockAlign: WrapAlignment.start,
              // 表格样式
              tableHead: const TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w600,
                color: Color(0xFF353535),
              ),
              tableBody: const TextStyle(
                fontSize: 13,
                color: Color(0xFF353535),
              ),
              tableBorder: TableBorder.all(
                color: const Color(0xFFCCCCCC),
                width: 1,
              ),
              tableCellsPadding: const EdgeInsets.symmetric(
                horizontal: 8,
                vertical: 5,
              ),
              // 水平分隔线
              horizontalRuleDecoration: BoxDecoration(
                border: Border(
                  top: BorderSide(
                    width: 1,
                    color: Colors.grey.shade400,
                  ),
                ),
              ),
              // 图片边距
              blockSpacing: 10,
              listIndent: 24,
            ),
          ),
      ),
    );
  }
}
